package com.ruoyi.fjtseac.service.impl;

import java.sql.Date;
import java.time.LocalDate;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.fjtseac.domain.dto.ApplicationFormDto;
import com.ruoyi.fjtseac.domain.dto.VolunteerDto;
import com.ruoyi.fjtseac.domain.po.ApplicationForm;
import com.ruoyi.fjtseac.domain.po.Volunteer;
import com.ruoyi.fjtseac.mapper.ApplicationFormMapper;
import com.ruoyi.fjtseac.util.DtoToPoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.fjtseac.mapper.VolunteerMapper;
import com.ruoyi.fjtseac.service.VolunteerService;

import javax.validation.Validator;

/**
 * 志愿者管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-07-15
 */
@Service
public class VolunteerServiceImpl extends BaseController implements VolunteerService
{
    private static final Logger log = LoggerFactory.getLogger(VolunteerServiceImpl.class);

    @Autowired
    private VolunteerMapper volunteerMapper;

    @Autowired
    private ApplicationFormMapper applicationFormMapper;

    @Autowired
    protected Validator validator;

    /**
     * 查询志愿者管理
     * 
     * @param volunteerId 志愿者管理主键
     * @return 志愿者管理
     */
    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public Volunteer selectVolunteerByVolunteerId(Long volunteerId)
    {
        return volunteerMapper.selectVolunteerByVolunteerId(volunteerId);
    }

    /**
     * 查询志愿者管理列表
     * 
     * @param volunteerDto 志愿者管理
     * @return 志愿者管理
     */
    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Volunteer> selectVolunteerList(VolunteerDto volunteerDto)
    {
        Volunteer volunteer = DtoToPoMapper.INSTANCE.toVolunteer(volunteerDto);
        return volunteerMapper.selectVolunteerList(volunteer);
    }


    /**
     * 同意志愿者申请管理
     * 
     * @param applicationFormDto 志愿者申请
     * @return 结果
     */
    @Override
    public AjaxResult agreeVolunteer(ApplicationFormDto applicationFormDto, String createBy)
    {
        ApplicationForm applicationForm = DtoToPoMapper.INSTANCE.toApplicationForm(applicationFormDto);
        Volunteer volunteer = new Volunteer();
        volunteer.setName(applicationForm.getName());
        volunteer.setGender(applicationForm.getGender());
        volunteer.setPhone(applicationForm.getPhone());
        volunteer.setJoinTime(Date.valueOf(LocalDate.now()));
        volunteer.setCreateBy(createBy);
        QueryWrapper<Volunteer>wrapper = new QueryWrapper();
        wrapper.eq("phone",volunteer.getPhone());
        if(volunteerMapper.selectCount(wrapper)>0){
            return AjaxResult.error("该用户已经存在");
        }

        volunteerMapper.insertVolunteer(volunteer);
        applicationForm.setFlag(2);//将状态值设置为0
        applicationForm.setOperationTime(Date.valueOf(LocalDate.now()));
        applicationFormMapper.updateById(applicationForm);
        return AjaxResult.success();
    }

    /**
     *志愿者新增管理
     * @param volunteerDto
     * @return
     */
    @Override
    public AjaxResult insertVolunteer(VolunteerDto volunteerDto,String createBy) {
        Volunteer volunteer = DtoToPoMapper.INSTANCE.toVolunteer(volunteerDto);

        QueryWrapper<Volunteer>wrapper = new QueryWrapper();
        wrapper.eq("phone",volunteer.getPhone());
        if(volunteerMapper.selectCount(wrapper)>0){
            return AjaxResult.error("该号码已经存在");
        }
        volunteer.setCreateBy(createBy);
        volunteer.setJoinTime(Date.valueOf(LocalDate.now()));
        return AjaxResult.success(volunteerMapper.insertVolunteer(volunteer));
    }

    /**
     * 修改志愿者管理
     * 
     * @param volunteerDto 志愿者管理
     * @return 结果
     */
    @Override
    public int updateVolunteer(VolunteerDto volunteerDto)
    {
        Volunteer volunteer = DtoToPoMapper.INSTANCE.toVolunteer(volunteerDto);
        return volunteerMapper.updateVolunteer(volunteer);
    }

    /**
     * 批量删除志愿者管理
     * 
     * @param volunteerIds 需要删除的志愿者管理主键
     * @return 结果
     */
    @Override
    public int deleteVolunteerByVolunteerIds(Long[] volunteerIds)
    {
        return volunteerMapper.deleteVolunteerByVolunteerIds(volunteerIds);
    }

    /**
     * 删除志愿者管理信息
     * 
     * @param volunteerId 志愿者管理主键
     * @return 结果
     */
    @Override
    public int deleteVolunteerByVolunteerId(Long volunteerId)
    {
        return volunteerMapper.deleteVolunteerByVolunteerId(volunteerId);
    }

    @Override
    public String importVolunteer(List<Volunteer> volunteersList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(volunteersList) || volunteersList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        Map<String,String> map = new HashMap<>();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");

        for(Volunteer volunteer : volunteersList) {
            // 验证是否存在这个用户
            Volunteer u = volunteerMapper.selectVolunteerByVolunteerPhone(volunteer.getPhone());
            if (u != null ) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、志愿者 " + volunteer.getName() + " 已存在");
            }else if(map.containsKey(volunteer.getPhone())){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、志愿者 " + volunteer.getName() + " 与志愿者 "+map.get(volunteer.getPhone())+" 号码相同");
                map.remove(volunteer.getPhone());//移除前一个拥有该号码的人
                map.put(volunteer.getPhone(),volunteer.getName());//添加新的拥有该号码的人
            }
            try{
                BeanValidators.validateWithException(validator,volunteer); //对象属性验证是否满足指定条件
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + volunteer.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            map.put(volunteer.getPhone(),volunteer.getName());
        }

        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，数据导入失败！共 " + failureNum + " 条数据/格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }

        for (Volunteer volunteer : volunteersList)
        {
                    volunteer.setCreateBy(operName);
                    volunteer.setJoinTime(Date.valueOf(LocalDate.now()));
                    volunteerMapper.insertVolunteer(volunteer);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + volunteer.getName() + " 导入成功");
        }
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }

    @Override
    public AjaxResult selectVolunteerPage(VolunteerDto volunteerDto) {

        startPage();
        List<Volunteer> list = selectVolunteerList(volunteerDto);
        return AjaxResult.success(getDataTable(list));

    }

}

